<template>
    <div class="pay-complete">
        <van-popup
            v-model="boxshow"
            round
            position="bottom"
            :get-container="getContainer"
            @close="closePop"
            class="popup-cont"
            :style="{
            height: '70%',
            fontSize: '0.32rem',
            overflowY: 'auto !important',
            }"
        >
            <!-- 顶部 -->
            <div class="popup-header">
            <div class="popup-header-title">{{ sheetInfo.title }}</div>
            <i
                class="van-icon van-icon-cross van-action-sheet__close"
                @click="closePop"
                v-show="sheetInfo.showClose"
            ></i>
            </div>
            <!-- 内容 -->
            <div class="content">
            <!-- loading组件 -->
            <loading v-if="showLoadingE" :fullscreen="isFullScreen"></loading>
            <!-- 支付状态 -->
            <pay-state
                :orderInfo="orderInfo"
                :isAlive="dj_isAlive"
                :isSDK="isSDK"
            ></pay-state>
            <!-- 引导加群 -->
            <lead-group 
                v-if="orderInfo.spu_id && boxshow"
                :orderInfo="orderInfo"
                :isCart="0"
                :isAlive="dj_isAlive"
            ></lead-group>
            <!-- 超级会员引导分享 -->
            <svipLeadSharePop
                :resourceType="orderInfo.resource_type"
                :resourceId="orderInfo.resource_id"
                :spuId="orderInfo.spu_id"
                @leadShareInfoLoaded="leadShareInfoLoaded"
                :isFromLive="true"
            ></svipLeadSharePop>
            <!-- 【营销】支付有礼 -->
            <pay-gifts
                :orderInfo="orderInfo"
                :cart="0"
                @loadingStatus="loadingStatus"
                :isAlive="dj_isAlive"
            ></pay-gifts></div
        ></van-popup>
    </div>
  </template>
  
  <script>
  import svipLeadSharePop from '@xiaoe/goose/lib/svip-lead-share-pop';
  import loading from "@xiaoe/goose/lib/loading";
  import * as api from "./api";
  import { sensorsViewPage } from "./utils/sensors_report";
  import PayState from "./components/PayState";
  import LeadGroup from "./components/LeadGroup";
  import PayGifts from "./components/PayGifts";
  import locale from '../../mixins/locale'
  
  export default {
    name: "PayComplete",
    components: {
      loading,
      PayState,
      LeadGroup,
      PayGifts,
      svipLeadSharePop
    },
    props: {
      boxshow: {
        type: Boolean,
        default: false,
      },
      popupContentStyle: {
        type: Object,
        default: () => {
          return {
            background: "#ffffff",
          };
        },
      },
      popupRoundStyle: {
        type: Object,
        default: () => {
          return {
            height: "70%",
          };
        },
      },
      // appen的dom
      getContainer: {
        type: String,
        default: 'body'
      }
    },
    computed:{
        isSDK(){
            // sdk
            let ua = navigator.userAgent.toLowerCase()
            return ua.indexOf('xiaoeapp') >-1
        },
    },
    mixins: [locale],
    data() {
      return {
        showPopup: this.boxshow, // 是否弹出确认订单弹框
        showLoadingE: false, // loading溜达鹅显示隐藏
        isFullScreen: false, //是否全屏显示溜达鹅
        sheetInfo: {
          // 确认订单弹框配置信息
          title: "",
          showClose: true,
          showBack: false,
          clickOverlayClose: false,
        },
        orderInfo: {
          // 订单信息
          app_id: "",
          order_id: "",
          resource_id: "",
          resource_type: "",
          spu_id: "",
          sku_id: "",
          has_package: 0,
          is_buy_gift: 0,
          spu_type: "",
        },
        hasSetLeadShare: false, // 是否设置了引导分享
        leadShareIsLoaded: false, // 请求获取引导分享的接口是否完成
        dj_order_id: '', // 点金计划完成页url传的order_id
        dj_isAlive: 0, // 点金计划完成页传dj_order_id默认是直播间
      };
    },
    watch: {
      boxshow: {
        handler: function(value) {
          if(!dj_order_id) {// 非点金计划才监听
            this.showPopup = value;
            if (value) {
                api.changealivePrefix("/_alive");
                this.handleInitOrderData();
                this.sensorsViewPageReport();
            } else {
              this.orderInfo = {
                app_id: "",
                order_id: "",
                resource_id: "",
                resource_type: "",
                spu_id: "",
                sku_id: "",
                has_package: 0,
                is_buy_gift: 0,
                spu_type: "",
              };
            }
          }
        },
      },
    },
    mounted() {
      let el = this.$el;
      let body = document.body;
      body.appendChild(el);
      // 点金计划完成页返回直播间
      this.dj_order_id = this.getQueryStr(window.location.href, "dj_order_id");
      if(this.dj_order_id){
        this.dj_isAlive = 1;
        api.changealivePrefix("/_alive");
        this.handleInitOrderData();
        this.sensorsViewPageReport();
      }
    },
    methods: {
        leadShareInfoLoaded({ hasSetLeadShare }) {
            this.hasSetLeadShare = hasSetLeadShare;
            this.leadShareIsLoaded = true;
        },
        loadingStatus(val) {
            this.showLoadingE = val;
        },
        handleInitOrderData() {
            this.initOrderData();
        },
        // 订单数据
        initOrderData() {
            this.loadingStatus(true);
            let params = {
                order_id: this.dj_order_id,
            };
            api
            .initOrderData(params)
            .then((res) => {
                if (res.code === 0) {
                    this.orderInfo = res.data;
                    // 点金计划支付完成返回自动打开弹窗
                    if(this.orderInfo.order_id && this.orderInfo.order_id === this.dj_order_id){
                        this.boxshow = true;
                        this.showPopup = true;
                        console.log(this.boxshow, this.showPopup, this.dj_order_id, '点金');
                    }
                }
            })
            .catch((err) => {
                console.error(err);
            })
            .finally(() => {
                this.loadingStatus(false);
            });
        },
        //数据上报
        sensorsViewPageReport() {
            sensorsViewPage({
                cmm1: "否",
                order_id: this.dj_order_id,
                cmm3: sessionStorage.getItem("cmm3")
                    ? sessionStorage.getItem("cmm3")
                    : "",
                cmm4: sessionStorage.getItem("cmm4")
                    ? sessionStorage.getItem("cmm4")
                    : "",
                cmm5: sessionStorage.getItem("cmm5")
                    ? sessionStorage.getItem("cmm5")
                    : "",
            });
        },
        // 关闭弹框
        closePop() {
            this.$emit("update:boxshow", false);
            this.$emit("payComplete");
            if(this.orderInfo.order_id && this.orderInfo.order_id === this.dj_order_id){
                this.boxshow = false;
                this.showPopup = false;
                // 关闭后删除dj_order_id，防止再次自动打开弹窗
                this.removeURLParameter("dj_order_id");
            }
        },
        showLoading() {
            this.$toast.loading({
                message: this.t('loading'),
                forbidClick: true,
                duration: 0,
            });
        },
        /**
         * 根据key获取url参数
         * @param key
         * @returns {*}
         */
        getQueryStr(url, key) {
            let LocString = String(url);
            let rs = new RegExp("(^|)" + key + "=([^&]*)(&|$)", "gi").exec(LocString);
            if (rs) {
                return rs[2];
            }
            return "";
        },
        removeURLParameter(paramKey) {
            let urlObject = new URL(window.location.href);
            // 获取URL查询参数对象
            let searchParams = urlObject.searchParams;
    
            // 若查询参数中存在指定的参数，则删除它
            if (searchParams.has(paramKey)) {
                searchParams.delete(paramKey);
            }
            console.log(urlObject);
            // 使用 replaceState 更新 URL
            window.history.replaceState({}, '', urlObject.href);
        },
    },
    destroyed() {
        sessionStorage.removeItem("cmm3");
        sessionStorage.removeItem("cmm4");
        sessionStorage.removeItem("cmm5");
    },
  };
  </script>
  
  <style lang="scss" scoped>
  .pay-complete {
    .popup-cont {
      .popup-header {
        max-width: 480px;
        width: 100%;
        position: fixed;
        z-index: 1;
        top: auto;
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 0.24rem 0;
        background: rgba(255, 255, 255, 1);
        border-radius: 0.32rem 0.32rem 0 0;
        min-height: 0.48rem;
        .popup-header-title {
          font-weight: 600;
          line-height: 0.48rem;
        }
        .van-action-sheet__left {
          position: absolute;
          top: 0.32rem;
          left: 0;
          color: #aaaaaa;
          font-size: 0.32rem;
        }
        .van-action-sheet__close {
          position: absolute;
          top: 0.32rem;
          right: 0;
          color: #aaaaaa;
          font-size: 0.32rem;
        }
      }
      .content {
        padding-top: 48px;
      }
    }
  }
  </style>
  